﻿#region ... Copyright Notice ...
/*
   Copyright 2008 Tyler Jensen

	Author: Tyler Jensen    http://www.tsjensen.com/blog

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Atrax.Library;

namespace Atrax.Utils
{
	public class HttpClient
	{
		private int maxBytes;
		private string localip;
		private bool followRedirectsOffHost;
		private int maxRedirects;
		private int readTimeout;

		public HttpClient(string localip, int readTimeoutSeconds, int maxBytes, int maxRedirects, bool followRedirectsOffHost)
		{
			if (localip != null)
				this.localip = localip;
			else
			{
				IPAddress[] adr = Dns.GetHostAddresses(Dns.GetHostName());
				if (adr.Length > 0)
					this.localip = adr[0].ToString();
			}
			this.readTimeout = readTimeoutSeconds * 1000; //convert to milliseconds
			this.maxBytes = maxBytes;
			this.maxRedirects = maxRedirects;
			this.followRedirectsOffHost = followRedirectsOffHost;
		}

		public InternetResponse ProcessRequest(InternetRequest request)
		{
			InternetResponse response = new InternetResponse() { Request = request };
			try
			{
				List<string> redirects = new List<string>();
				int attempts = 0;
				InternetResponse tempResponse = GetResponse(request);
				while ((tempResponse == null || tempResponse.StatusCode.StartsWith("9")) && attempts < 3)
				{
					tempResponse = GetResponse(request);
					attempts++;
				}
				if (tempResponse == null)
				{
					response.StatusCode = "902";
					response.StatusDescription = "unable to retrieve page";
				}
				else
				{
					response = tempResponse;
					response.Request = request;
				}
			}
			catch (Exception e)
			{
				response.StatusCode = "999";
				response.StatusDescription = e.ToString().Replace("\n", "").Replace("\r", "");
			}
			return response;
		}

		private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
		{
			if (retryCount < 10 && this.localip != null)
				return new IPEndPoint(IPAddress.Parse(this.localip), 0);
			else
				return new IPEndPoint(IPAddress.Any, 0);
		}

		private InternetResponse GetResponse(InternetRequest request)
		{
			string requestUrl = Uri.EscapeUriString(Uri.UnescapeDataString(request.Url)); //make sure it's clean because .Create will parse into Uri
			InternetResponse response = new InternetResponse();
			try
			{
				if (!Uri.IsWellFormedUriString(requestUrl, UriKind.Absolute))
				{
					response.StatusCode = "905";
					response.StatusDescription = "malformed URI";
					return response; //bail out early if not an absolute URI
				}
				HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requestUrl);
				req.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
				req.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
				req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; InfoPath.1; .NET CLR 1.1.4322)";
				req.Timeout = this.readTimeout;
				req.Method = request.Method;
				if (request.ContentType != null)
				{
					req.ContentType = request.ContentType;
				}
				if (request.CustomHeaders != null && request.CustomHeaders.Count > 0)
				{
					foreach (KeyValuePair<string, string> pair in request.CustomHeaders)
					{
						req.Headers.Add(pair.Key, pair.Value);
					}
				}
				if (request.Method == "POST")
				{
					req.ContentLength = request.PostData.Length;
					using (Stream up = req.GetRequestStream())
					{
						using (StreamWriter sw = new StreamWriter(up))
						{
							sw.Write(request.PostData);
							sw.Flush();
						}
					}
				}
				using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
				{
					using (Stream s = resp.GetResponseStream())
					{
						byte[] data = this.ReadStreamData(s);
						if (data != null)
						{
							response.Body = new byte[data.Length];
							Array.Copy(data, response.Body, data.Length);
						}
						response.ContentType = resp.ContentType;
						response.Headers = resp.Headers;
						response.StatusDescription = resp.StatusDescription;
						int scode = (int)resp.StatusCode;
						response.StatusCode = scode.ToString(); //resp.StatusCode.ToString();
						response.ProtocolVersion = resp.ProtocolVersion.ToString();
					}
				}
			}
			catch (WebException we)
			{
				response.StatusCode = "900";
				response.StatusDescription = we.Status.ToString() + we.Message;
			}
			catch (Exception e)
			{
				response.StatusCode = "903";
				response.StatusDescription = "Unknown: " + e.ToString();
			}
			return response;
		}

		private byte[] ReadStreamData(Stream s)
		{
			byte[] data = null;
			int tries = 0;
			while (data == null && tries < 3) //try 3 times before giving up on reading data
			{
				if (tries > 0) System.Threading.Thread.Sleep(50); //wait on the thread 50ms 
				while (true)
				{
					byte[] readdata = new byte[2048];
					int recv = 0;
					try
					{
						recv = s.Read(readdata, 0, readdata.Length); //.NET 2.0 timeout throws error otherwise waits to read infinitely
					}
					catch
					{
						recv = 0; //TODO - deal with timeout, use something to mark it and set the ResponseCode and ResponseMessage
					}
					if (recv > 0)
					{
						if (data != null) //append
						{
							byte[] comb = new byte[data.Length + recv];
							Array.Copy(data, 0, comb, 0, data.Length); //copy data to combination
							Array.Copy(readdata, 0, comb, data.Length, recv); //copy readdata to combination
							data = new byte[comb.Length]; //remake data
							Array.Copy(comb, data, comb.Length); //copy combination to data
						}
						else //copy to data for first time
						{
							data = new byte[recv];
							Array.Copy(readdata, 0, data, 0, recv);
						}
						if (data.Length > this.maxBytes) break; //jump out of stream after we reach our set max
					}
					else
					{
						break;
					}
				}
				tries++;
			}
			return data;
		}
	}
}